package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    public static final String ARTICLE_INDEXNAME="app_info_article";

    @Autowired
    EsService<SearchArticleVO> esService;

    @Autowired
    ApUserSearchService apUserSearchService;

    @Value("${file.minio.readPath}")
    String readPath;

    @Override
    public ResponseResult search(UserSearchDTO userSearchDto) {
        // 1. 校验参数   关键字
        String searchWords = userSearchDto.getSearchWords();
        if(StringUtils.isBlank(searchWords)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"搜索关键字不能未空");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        userSearchDto.setEntryId(user!=null ? user.getId() : null);
        apUserSearchService.insert(userSearchDto);
        // 2. 构建es的搜索条件对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 2.1 创建布尔请求  boolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 2.2 根据关键词  使用match分词  查询title字段
        boolQueryBuilder.must(QueryBuilders.matchQuery("title",searchWords));
            // 2.3 根据最小时间   使用range查询 publishTime字段
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime()));
        sourceBuilder.query(boolQueryBuilder);
        // 2.4 封装高亮条件    哪个字段   前置    后置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);

        // 2.5 按照发布时间降序排序
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        // 2.6 设置分页
        sourceBuilder.size(userSearchDto.getPageSize());
        // 3. 调用工具类的search方法  查询es索引库
        // SearchSourceBuilder 用于构建所有的参数条件    request.source().xxxx
        PageResponseResult searchResult = esService.search(sourceBuilder, SearchArticleVO.class, ARTICLE_INDEXNAME);
        // 4. 拼接静态页前缀
        List<SearchArticleVO> articleVOList = (List<SearchArticleVO>)searchResult.getData();
        if (CollectionUtils.isNotEmpty(articleVOList)){
            for (SearchArticleVO searchArticleVO : articleVOList) {
                searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
            }
        }
        return searchResult;
    }
}
